package com.shujia.day19;

import java.sql.*;
import java.util.HashMap;
import java.util.Properties;
import java.util.Scanner;

public class Code01UserLogin {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        /*
            创建表：
            CREATE TABLE user_tb(
                user_name varchar(255) ,
                passwd varchar(255)
            );
         */

//        String driver = "com.mysql.jdbc.Driver";
//        String url = "jdbc:mysql://192.168.163.100:3306/stu?useSSL=false&useUnicode=true&characterSet=utf8";
//        String user = "root";
//        String passwd = "";

        HashMap<String, String> properties = new HashMap<>();
        for (String arg : args) {
            System.out.println("接收到参数：" + arg);
            String[] split = arg.split("=");
            properties.put(split[0], split[1]);
        }

//        driver = properties.get("driver");
//        url = properties.get("url");
//        user = properties.get("user");
//        passwd = properties.get("passwd");




        String driver = properties.getOrDefault("driver","com.mysql.jdbc.Driver");
        String url = properties.getOrDefault("url","jdbc:mysql://192.168.163.100:3306/stu?useSSL=false&useUnicode=true&characterSet=utf8");
        String user = properties.getOrDefault("user","root");
        String passwd = properties.getOrDefault("passwd","");


        // 需求：从控制台输入用户名以及密码，并从Mysql数据库中查询数据，如果查询结果一致，那么显示登录成功，否则登录失败


        Class.forName(driver);
        Connection connection = DriverManager.getConnection(url, user, passwd);
        Statement statement = connection.createStatement();


        String userName = "";
        String passWD = "";
        Scanner scanner = new Scanner(System.in);
        System.out.println("欢迎登录XXX相亲平台");
        System.out.println("有缘人请输入用户名：");

        if (scanner.hasNext()) {
            userName = scanner.nextLine();
        }
        System.out.println("请输入密码：");
        if (scanner.hasNext()) {
            passWD = scanner.next();
        }

//        user_name='老邢' or '1=1'

        // 4.对SQL进行执行
        String sql = "select * from user_tb where user_name='" + userName + "'";  // 加上单引号 否则认为是一个数值
        System.out.println(sql);
        ResultSet resultSet = statement.executeQuery(sql);

        // 5.如果有数据返回，那么需要对数据进行做迭代

        if (!resultSet.next()) {
            System.out.println("您输入的用户不存在，请加入相亲一家人..");
        } else {
            String queryPasswd = resultSet.getString("passwd");
            if (queryPasswd.equals(passWD)) {
                System.out.println("登录成功，尽情享受相亲时光吧..");
            } else {
                System.out.println("密码不对，请重新输入，否则将错过一份美好姻缘");
            }
        }


        statement.close();
        connection.close();
    }
}
